package com.another.bidservice.service.impl;

import com.another.bidservice.dao.jpa.PlanBidderJPADao;
import com.another.bidservice.dao.jpa.PlanJPADao;
import com.another.bidservice.dao.mapper.PlanDao;
import com.another.bidservice.entity.TPlan;
import com.another.bidservice.entity.TPlanBidder;
import com.another.bidservice.entity.TPlanMain;
import com.another.bidservice.dao.jpa.PlanMainJPADao;
import com.another.bidservice.dao.mapper.PlanMainDao;
import com.another.bidservice.service.IPlanMainService;
import com.another.common.enums.CodeRuleEnum;
import com.another.common.enums.Enums;
import com.another.common.utils.common.DateUtil;
import com.another.common.utils.common.EmptyUtil;
import com.another.common.utils.common.MyException;
import com.another.common.utils.result.Result;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class PlanMainServiceImpl extends BaseServiceImpl implements IPlanMainService {

    private Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private PlanMainDao planmainDao;

    @Autowired
    private PlanMainJPADao planmainJPADao;

    @Autowired
    private PlanJPADao planJPADao;

    @Autowired
    private PlanDao planDao;

    @Autowired
    private PlanBidderJPADao planBidderJPADao;

    @Override
    public Result getList(TPlanMain tPlanMain) {
        String sql = "select * from t_plan_main";
        List<TPlanMain> list = planmainDao.getList(sql);

        List<TPlan> plans=planJPADao.findAllByMainNoIn(list.stream().map(TPlanMain::getMainNo).collect(Collectors.toList()));
        List<TPlanBidder> bidders=planBidderJPADao.findAllByMainNoIn(list.stream().map(TPlanMain::getMainNo).collect(Collectors.toList()));

        list.stream().forEach(i->{

            i.setPlans(new ArrayList<>());
            i.setPlanBidders(new ArrayList<>());

            plans.stream().forEach(x->{
                if (i.getMainNo().equals(x.getMainNo())) {
                    i.getPlans().add(x);
                }
            });

            bidders.stream().forEach(x->{
                if (i.getMainNo().equals(x.getMainNo())) {
                    i.getPlanBidders().add(x);
                }
            });

        });

        if (EmptyUtil.isEmpty(list)) {
            return Result.success("没有查询到数据！", "");
        } else {
            return Result.success(list);
        }
    }


    @Override
    public Result insertList(List<TPlanMain> tPlanMains) {
        int ret = planmainDao.insertList(tPlanMains);
        if (ret == tPlanMains.size()) {
            return Result.success("添加成功！", "");
        } else {
            throw new MyException(101, "添加失败！");
        }
    }


    @Override
    public Result deleteList(List<Integer> rowid) {
        int ret = planmainDao.deleteList(rowid);
        if (ret == rowid.size()) {
            return Result.success("删除成功！", "");
        } else {
            throw new MyException(101, "删除失败！");
        }
    }

    @Override
    public Result updateList(List<TPlanMain> tPlanMains) {
        try {
            int ret = planmainDao.updateList(tPlanMains);
            return Result.success("修改成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }


    @Override
    public Result insertPlanMain(TPlanMain main) {
        try {

            if (EmptyUtil.isEmpty(main.getPlans())) {
                return Result.error("缺少待发布资源参数！");
            }

            if (EmptyUtil.isEmpty(main.getSourceType())) {
                return Result.error("来源类型不能为空！");
            }
            if (EmptyUtil.isEmpty(main.getPlanType())) {
                return Result.error("发布类型不能为空！");
            }
            if (EmptyUtil.isEmpty(main.getBidType())) {
                return Result.error("竞价类型不能为空！");
            }
            if (Enums.BidType.PART.getCode().equals(main.getBidType()) && EmptyUtil.isEmpty(main.getPlanBidders())) {
                return Result.error("请选择竞价人！");
            }

            if (Enums.SourceType.TIMING_GENERATION.getCode().equals(main.getSourceType()) && EmptyUtil.isEmpty(main.getScheduledRelease())) {
                return Result.error("请选择定时发布时间！");
            }

            if (EmptyUtil.isEmpty(main.getBidStartDate())) {
                return Result.error("请选择竞价开始时间！");
            }

            if (EmptyUtil.isEmpty(main.getBidEndDate())) {
                return Result.error("请选择竞价结束时间！");
            }

            //查看待发布资源信息
            List<TPlan> plans = planJPADao.findAllByPlanNoInAndPlanStatusIs(main.getPlans().stream().map(TPlan::getPlanNo).collect(Collectors.toList()), Enums.PlanStatus.INITIAL.getCode());

            if (EmptyUtil.isEmpty(plans)) {
                return Result.error("没有查询到能发布的资源！");
            }

            //判断待发布资源货主是否一致
            Map<String, List<TPlan>> planMap = plans.stream().collect(Collectors.groupingBy(TPlan::getShipperId));
            if (EmptyUtil.isEmpty(planMap) || planMap.keySet().size() != 1) {
                return Result.error("请选择相同的待发布资源！");
            }

            //生成货盘编号
            String mainNo = generateNumber(CodeRuleEnum.PALLET_MASTER_NUMBER.getCode());

            main.setMainNo(mainNo);
            main.setCreateId(main.getRequestUserId());
            main.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());
            main.setShipperId(plans.get(0).getShipperId());
            main.setShipperCompanyId(plans.get(0).getShipperCompanyId());
            main.setTransType(plans.get(0).getTransType());
            main.setProxyType(plans.get(0).getProxyType());

            if (Enums.SourceType.POST_NOW.getCode().equals(main.getSourceType())) {
                main.setPlanStatus(Enums.PlanStatus.PUBLISHED.getCode());
                main.getPlans().stream().forEach(i -> {
                    i.setPlanStatus(Enums.PlanStatus.PUBLISHED.getCode());
                });
            } else if (Enums.SourceType.TIMING_GENERATION.getCode().equals(main.getSourceType())) {
                main.setPlanStatus(Enums.PlanStatus.TO_BE_SCHEDULED_FOR_RELEASE.getCode());
                main.getPlans().stream().forEach(i -> {
                    i.setPlanStatus(Enums.PlanStatus.TO_BE_SCHEDULED_FOR_RELEASE.getCode());
                });
            }


            main.getPlans().stream().forEach(i -> {
                i.setMainNo(mainNo);
                i.setUpdateId(main.getRequestUserId());
            });


            if (Enums.BidType.PART.getCode().equals(main.getBidType())) {
                main.getPlanBidders().stream().forEach(i -> {
                    i.setMainNo(mainNo);
                    i.setCreateId(main.getRequestUserId());
                    i.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());
                });
                //新增竞价人
                planBidderJPADao.saveAll(main.getPlanBidders());
            }

            //修改待发布资源
            planDao.updateList(main.getPlans());

            planmainJPADao.save(main);
            return Result.success("添加成功！", main);
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "添加失败！");
        }
    }

    @Override
    public Result updatePlanMain(TPlanMain main) {
        try {

            if (EmptyUtil.isEmpty(main.getMainNo())) {
                return Result.success("货盘主单号必传！");
            }

            TPlanMain getMain = planmainJPADao.findTopByMainNo(main.getMainNo());
            if (EmptyUtil.isEmpty(getMain)) {
                return Result.success("根据货盘号没有查询到货盘信息！");
            }

            if (Enums.PlanStatus.BID.getCode().equals(getMain.getPlanStatus()) || Enums.PlanStatus.END_OF_AUCTION.getCode().equals(getMain.getPlanStatus()) || Enums.PlanStatus.DEAL_DONE.getCode().equals(getMain.getPlanStatus())) {
                return Result.success("当前货盘状态不支持修改！");
            }

            List<TPlan> updateplans = new ArrayList<>();

            //需要调整Plan信息
            if (Enums.SourceType.POST_NOW.getCode().equals(main.getSourceType())) {
                main.setPlanStatus(Enums.PlanStatus.PUBLISHED.getCode());
                //修改货盘状态为已发布
                TPlan plan = new TPlan();
                plan.setMainNo(main.getMainNo());
                plan.setPlanStatus(Enums.PlanStatus.PUBLISHED.getCode());
                updateplans.add(plan);
            } else if (Enums.SourceType.TIMING_GENERATION.getCode().equals(main.getSourceType())) {
                //修改货盘状态为已发布
                TPlan plan = new TPlan();
                plan.setMainNo(main.getMainNo());
                plan.setPlanStatus(Enums.PlanStatus.TO_BE_SCHEDULED_FOR_RELEASE.getCode());
                updateplans.add(plan);
            }


            //是否属于部分竞价
            if(EmptyUtil.isNotEmpty(main.getBidType())) {
                if (Enums.BidType.ALL.getCode().equals(main.getBidType())) {
                    planBidderJPADao.deleteAllByMainNo(main.getMainNo());
                } else if (Enums.BidType.PART.getCode().equals(main.getBidType()) && EmptyUtil.isNotEmpty(main.getPlanBidders())) {
                    planBidderJPADao.deleteAllByMainNo(main.getMainNo());
                    main.getPlanBidders().stream().forEach(i->{
                        i.setMainNo(main.getMainNo());
                        i.setCreateId(main.getCreateId());
                        i.setCreateDate(DateUtil.getNowDateByyyyyMMddHHmmss());
                    });
                    planBidderJPADao.saveAll(main.getPlanBidders());
                }

            }

            if (EmptyUtil.isNotEmpty(updateplans)) {
                planDao.updateListV2(updateplans);
            }

            main.setUpdateId(main.getRequestUserId());
            int ret = planmainDao.updatePlanMain(main);
            return Result.success("修改成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "修改失败！");
        }
    }

    @Override
    public Result deletePlanMain(TPlanMain tPlanMain) {
        try {
            int ret = planmainDao.deletePlanMain(tPlanMain);
            return Result.success("删除成功！", "");
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(101, "删除失败！");
        }
    }
}



